package com.topdt.jbpm.web.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.util.FileUtil;
import com.thx.common.web.SessionInfo;
import com.thx.common.web.WebConstant;
import com.topdt.jbpm.identity.IdentityService;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.Todo;
import com.topdt.jbpm.model.WorkAttach;
import com.topdt.jbpm.service.AttachmentService;
import com.topdt.jbpm.service.JbpmService;
import com.topdt.jbpm.utils.PdfThread;
import com.topdt.jbpm.web.SessionUserUtil;
/**
 *
 * @创建日期 2013-4-19 <br>
 * @作者: 王阿敏 <br>
 * @模块: 起草工作添加附件<br>
 * @描述: <br>
 * @修改历史: <br>
 */
@Namespace("/workflow")
@Action(value = "attachment",
		results = {
		@Result(name = "show", location = "/page/biz/templates/attachment.jsp"),
		@Result(name = "flashviewFile", location = "/pages/workflow/fileCabinet/flashviewFile.jsp"),
		@Result(name = "viewFile_pic", location = "/pages/workflow/fileCabinet/viewFile_pic.jsp"),
		@Result(name = "viewFile", location = "/pages/workflow/fileCabinet/viewFile_office.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" }),
		@Result(name = "jsonStr", type = "json", params = { "root", "jsonStr" })
		}
)
@Controller
@Scope("prototype")
public class AttachmentAction extends CurdAction<WorkAttach> {

	private static final long serialVersionUID = 1L;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private JbpmService jbpmService;
	@Autowired
	private IdentityService identityService;
	private List<WorkAttach> workAttachList;
	private CommonsMultipartFile file;
	private String uploaderId;
	private String name;
	private String sessionid;
	private String attachId;
	private String fileId;

	private String swfFileName;//预览文件的swf绝对路径
	private String annexId;// 保存文件的id
	private String jsonStr;
	private String imageSrc;
	/**
	 * ADD END
	 */
	/**
     * 用File数组来封装多个上传文件域对象
     */
	private File[] upload;
	/**
     * 用String数组来封装多个上传文件名
     */
	private String[] uploadFileName;

	/**
	 * 保存上传的附件
	 * 建立日期 : June 25, 2013 6:30:22 PM<br>
	 * 作者 : wangamin<br>
	 * 修改： sunyaofei 2013-08-11
	 * @return
	 */
	public void saveUploadFile(){
		logger.debug("<进入>:saveUploadFile方法  保存上传的附件");
		HttpServletRequest request =  getRequest();
		String comId = AppContext.getCurrentComId();
		if(StringUtils.isBlank(comId)&&getSession().getAttribute(WebConstant.KEY_USER)!=null){//zhangyong20160302
			comId = ((SessionInfo)(getSession().getAttribute(WebConstant.KEY_USER))).getComId();
		}
		User user  = SessionUserUtil.getCurrentUser();
		Date d = new Date();
		long uploadTime = d.getTime();

		// 当前正在处理的文件分块序号
		int chunk = Integer.valueOf(request.getParameter("chunk"));
		//为续传创建的流,连接原先的文件
		InputStream in = null;

		//boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		try {
			// 处理每个要上传的文件
	        for (int i = 0; i < upload.length; i++) {
	            if (upload[i].length() != 0) {
	                // 根据服务器的文件保存地址和原文件名创建目录文件全路径
	            	String mainUploadPath = AppContext.getProperties("uploadPath");
	            	String path=AppContext.getProperties("fileUploadPath");
	            	String dstPath="";//最终保存的路径
	            	//重命名文件名 BY LCX 20141205
	            	String reFileName="";
                    File fileHome =new File(path);
                    if (!fileHome.exists()) {
						fileHome.mkdirs();
					}
//                    path = path.substring(1,path.length())+"/"+OAConstant.ANNEX_TYPE_NAME_ATTACHMENT+"/"+enterpriseId+"/"+rename(uploadFileName[i]);
                    path = path+"/"+rename(uploadFileName[i]);
                    dstPath = mainUploadPath+path;
                    /* 1. 先把数据插入到数据库 ，顺便查出保存到本地的重命名文件*/
                    Todo todo = new Todo();
                    if(StringUtils.isBlank(entity.getTodoId())){
                    	if(StringUtils.isNotBlank(entity.getWorkId())){
                    		todo = jbpmService.findTodoByWorkAndUser(entity.getWorkId(), user.getId());
                    	}
                    }else{
                    	todo = jbpmService.getTodoById(entity.getTodoId());
                    }
                    List<WorkAttach> attachListNew = attachmentService.getAttachByCondition(uploadFileName[i], todo.getToUserId(), todo.getTodoId());

                    String realName = uploadFileName[i];
                    WorkAttach workAttach = null;
                    if(chunk == 0){
                    	workAttach = new WorkAttach();
                    	workAttach.setActivityName(todo.getActivityName());
                    	workAttach.setHandlerName(todo.getToUserId());
                    	workAttach.setNowFullName(dstPath);


//                    	List<WorkAttach> list = attachmentService.getAttachList(uploadFileName[i], todo.getToUserId(), todo.getTodoId());
//                    	if(attachListNew.size()>0){
//                    		for(int m=0;m<list.size();m++){
//                    			WorkAttach att = list.get(m);
//                    			int cc = (list.size()-m);
//                    			if(cc>1){
//                    				String interceptName = uploadFileName[i].substring(0,uploadFileName[i].lastIndexOf("."));
//                    				String changeName = interceptName+"("+(list.size()-m-1)+")";
//                    				String uploadName = changeName+uploadFileName[i].substring(uploadFileName[i].lastIndexOf("."),uploadFileName[i].length());
//                    				att.setRealName(uploadName);
//                    				attachmentService.saveorUpdate(att);
//                    			}else{
//                    				att.setRealName(uploadFileName[i]);
//                    				attachmentService.saveorUpdate(att);
//                    			}
//                    		}
//                    		String interceptName = uploadFileName[i].substring(0,uploadFileName[i].lastIndexOf("."));
//            				String changeName = interceptName+"("+list.size()+")";
//            				String uploadName = changeName+uploadFileName[i].substring(uploadFileName[i].lastIndexOf("."),uploadFileName[i].length());
//                    		realName = uploadName;
//                    	}

                    	workAttach.setRealName(realName);
//                    	workAttach.setUploadTime(new Timestamp(uploadTime));
                    	workAttach.setCompanyId(comId+"");
                    	workAttach.setTodoId(todo.getTodoId());
                    	workAttach.setWorkId(entity.getWorkId());
                    	workAttach.setFileId(entity.getFileId());

                    	workAttach.setTempName(uploadFileName[i]);
//                    	attachmentService.saveorUpdate(workAttach);
                    }

                    WorkAttach attach = null;
//                    List<WorkAttach> attachList = attachmentService.getAttachList(uploadFileName[i], todo.getToUserId(), todo.getTodoId());
//                    if(attachList.size()>0){
//                    	attach= attachList.get(0);
//                    }


                    /* 2 . 保存文件到本地*/
                    if(upload[i]!=null && chunk == 0){
                    	if(attach!=null){
                    		if(StringUtils.isNotBlank(attach.getNowFullName())){
                    			File file = new File(attach.getNowFullName());

                    			String nowfullName = attach.getNowFullName();
                    			String fileName = nowfullName.substring(nowfullName.lastIndexOf("/"),nowfullName.length());
                    			/*重新命名文件名 BY LCX */
                    			reFileName=nowfullName.substring(nowfullName.lastIndexOf("/")+1);
                    			String  newPath = path.substring(0,path.lastIndexOf("/"))+fileName;
        				    	if(file.exists()){
        				    		file.delete();
        				    		//上传新文件
        				    		FileUtil.copyFile(upload[i].getAbsolutePath(), mainUploadPath+newPath,true);
            	                	//转换文件
            	                	PdfThread t = new PdfThread(uploadFileName[i], newPath, reFileName);
            	                	t.start();
        				    	}else{
        				    		//上传文件
        				    		FileUtil.copyFile(upload[i].getAbsolutePath(), mainUploadPath+newPath,true);
            	                	//转换文件
            	                	PdfThread t = new PdfThread(uploadFileName[i], newPath, reFileName);
            	                	t.start();
        				    	}
                    		}
                    	}else{
                    		//上传文件
    				    	FileUtil.copyFile(upload[i].getAbsolutePath(), path,true);
    	                	//转换文件
    	                	PdfThread t = new PdfThread(uploadFileName[i], path, reFileName);
    	                	t.start();
                    	}


			    	}
                    //更新附件  wangxufeng add 2015-01-21
                    if(StringUtils.isNotBlank(reFileName) && workAttach != null){
                    	String fileType = reFileName.substring(reFileName.lastIndexOf(".")+1, reFileName.length());
                    	if(!fileType.equals("pdf")){
                    		String fileUploadPathHtml = AppContext.getProperties("fileUploadPathHtml");
                    		workAttach.setHtmlFullName(fileUploadPathHtml+"/"+reFileName.replaceFirst(fileType, "html"));
                    	}
                    	String fileUploadPathSwf = mainUploadPath+AppContext.getProperties("fileUploadPathSwf");
                    	workAttach.setSwfFullName(fileUploadPathSwf+"/"+reFileName.replaceFirst(fileType, "swf"));
//                    	attachmentService.saveorUpdate(workAttach);
                    }
                    /*     update over            */
                    if(upload[i]!=null && chunk > 0){
			    		//追加文件
                    	in = new FileInputStream(upload[i]);
                    	if(StringUtils.isNotBlank(attach.getNowFullName())){
                    		AttachmentAction.uploadFile(in, attach.getNowFullName(), true);
                    	}
			    	}

	            }
	        }
		} catch (Exception e) {
			logger.error("<错误>:保存上传附件失败",e);
		}

	}

	/**
	 * 文件重命名
	 * @param fileName  文件名
	 * @return 重命名后的文件名
	 */

	public static String rename(String fileName){
        String extName = ""; // 保存文件拓展名
		Random r = new Random();
		int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // 时间格式化的格式
		String nowTimeStr = sDateFormat.format(new Date()); // 保存当前时间
		// 获取扩展名
		if (fileName.lastIndexOf(".") >= 0) {
			extName = fileName.substring(fileName.lastIndexOf("."));
		}
		//将txt文件格式换为odt，解决txt中文乱码问题   wangxufeng add 2015-01-26
		//extName = extName.equals(".txt")?".odt":extName;
		String newFileName = nowTimeStr + rannum + extName; // 文件重命名后的名字
		return newFileName;

	}
	/**
	 * 续传文件
	 * @param is 文件输入流
	 * @param fullName 保存文件绝对路径
	 * @param isCopy 如果出现同名文件，是否追加
	 * @return
	 */
	public static boolean  uploadFile(InputStream is,String fullName,boolean isAppend){
		int chunkSize = 50*1024*1024;
		try {
			OutputStream bos = new FileOutputStream(fullName,isAppend);
			int bytesRead = 0;
			byte[] buffer = new byte[chunkSize];
			while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			bos.close();
			is.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 跳转到添加附件页面
	 * 建立日期 : June 25, 2013 5:41:50 PM<br>
	 * 作者 : wangamin<br>
	 * @return
	 */
	public String show(){
		logger.debug("<进入>:show方法   跳转到添加附件页面");
		List<WorkAttach> workAttachs = attachmentService.getWorkAttachByWorkId(entity.getWorkId());
		 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 List<WorkAttach> workAttachList = new ArrayList<WorkAttach>();
		 if(workAttachs!=null){
			 for(WorkAttach work:workAttachs){
					String uploadTime = sdf.format(work.getUploadTime());
					Timestamp ts = Timestamp.valueOf(uploadTime);
//					work.setUploadTime(ts);
					workAttachList.add(work);
			 }
		 }
		 jsonStr = com.alibaba.fastjson.JSON.toJSONString(workAttachList);
		return "jsonStr";
	}

	/**
	 * 删除附件
	 * 建立日期 : July 16, 2013 5:41:50 PM<br>
	 * 作者 : wangamin<br>
	 * @return
	 */
	public void deleteAttach(){
		logger.debug("<进入>:deleteAttach方法   删除附件");
		int msg = 0;
		WorkAttach attach = null;
		//删除物理文件
		if(StringUtils.isNotBlank(attachId)){
			attach = attachmentService.getAttachById(attachId);
		}else if(StringUtils.isNotBlank(fileId)&&StringUtils.isNotBlank(name)){
			attach = attachmentService.getWorkAttachByFileIdAndName(fileId,name);
		}
		if(attach != null){
			//删除数据库文件
			attachmentService.deleteAttach(attach);
			workAttachList = attachmentService.getWorkAttachByWorkId(entity.getWorkId());
		}
		 try {
			writeJson(msg+"");
		} catch (IOException e) {
			logger.error("<错误>:删除附件失败",e);
		}

	}


	//--文件下载
	public void downloadFile() throws Exception{
		logger.debug("<进入>:downloadFile方法   文件下载");
		HttpServletResponse response =ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		WorkAttach attach = null;

		if(StringUtils.isNotBlank(attachId)){
			attach = attachmentService.getAttachById(attachId);
		}else if(StringUtils.isNotBlank(fileId)&&StringUtils.isNotBlank(name)){
			name = java.net.URLDecoder.decode(name,"UTF-8");
			attach = attachmentService.getWorkAttachByFileIdAndName(fileId,name);
		}

		InputStream is;
		try {
			is = new FileInputStream(attach.getNowFullName());
			  int len=0;
		        byte []buffers=new byte[1024];
		        response.reset();
		        String fileName ="";
		        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
		        	fileName =new String(attach.getRealName().getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
		        }else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
		        	fileName = URLEncoder.encode(attach.getRealName(), "UTF-8");//IE浏览器
		        }else if(request.getHeader("User-Agent").indexOf("Mozilla") >= 0){
		        	//判断高版本的iE浏览器 add 2015-01-06 wangxufeng
					fileName = URLEncoder.encode(attach.getRealName(), "UTF-8");
				}else if(request.getHeader("User-Agent").toLowerCase().indexOf("chrome") > 0){
		        	fileName = URLEncoder.encode(attach.getRealName(), "UTF-8");
		        }else{
		        	fileName = URLEncoder.encode(attach.getRealName(), "UTF-8");
		        }
		        response.setContentType("application/x-msdownload");
		        response.addHeader("Content-Disposition", "attachment;filename=\""+fileName+"\"");
		        //把文件内容通过输出流打印到页面上供下载
		        while((len=is.read(buffers))!=-1){
		           OutputStream os=response.getOutputStream();
		           os.write(buffers, 0, len);
		        }
		        is.close();
		} catch (FileNotFoundException e) {
			logger.error("下载文件失败",e);
		}


	}
	/**
	 * 在线查看office文件用金格插件
	 * @author zhangyong
	 * @date   2015-1-6 上午11:53:10
	 * @return
	 */
	public String viewFileOnline(){
		logger.debug("<进入>:viewFileOnline方法   在线查看office文件(借助金格插件)");
		if(StringUtils.isNotBlank(attachId)){
			entity = attachmentService.getAttachById(attachId);
		}else if(StringUtils.isNotBlank(fileId)&&StringUtils.isNotBlank(name)){
			try {
				name = java.net.URLDecoder.decode(name,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("<错误>:在线查看office文件失败",e);
			}
			entity = attachmentService.getWorkAttachByFileIdAndName(fileId,name);
		}
		HttpServletRequest request =  getRequest();
		request.setAttribute("annexPathAndName", entity.getNowFullName());
		return  "viewFile" ;
	}


	/**
	 * 在线预览文件
	 * @author BY LCX
	 * @date   20141205
	 * @return
	 */
	public String flashviewFile( ) {
		logger.debug("<进入>:flashviewFile方法   在线预览文件");
		WorkAttach attach = new WorkAttach();
		if(StringUtils.isNotBlank(attachId)){
			attach = attachmentService.getAttachById(attachId);
		}else if(StringUtils.isNotBlank(fileId)&&StringUtils.isNotBlank(name)){
			try {
				name = java.net.URLDecoder.decode(name,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("<错误>:在线预览文件失败",e);
			}
			attach = attachmentService.getWorkAttachByFileIdAndName(fileId,name);
		}
		if(attach!=null&&StringUtils.isNotBlank(attach.getNowFullName())){
			String nowFullName = attach.getNowFullName().substring(attach.getNowFullName().lastIndexOf("/")+1);
			swfFileName  = AppContext.getProperties("fileUploadPathSwf")+"/"+nowFullName.substring(0,nowFullName.lastIndexOf("."))+".swf";
		}
		return  "flashviewFile" ;
	}

	public String viewImageFile(){
		logger.debug("<进入>:viewImageFile方法    在线查看图片文件");
		if(StringUtils.isNotBlank(attachId)){
			entity = attachmentService.getAttachById(attachId);
		}else if(StringUtils.isNotBlank(fileId)&&StringUtils.isNotBlank(name)){
			try {
				name = java.net.URLDecoder.decode(name,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("<错误>:在线查看图片文件失败",e);
			}
			entity = attachmentService.getWorkAttachByFileIdAndName(fileId,name);
		}
		return "viewFile_pic";
	}

	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public List<WorkAttach> getWorkAttachList() {
		return workAttachList;
	}

	public void setWorkAttachList(List<WorkAttach> workAttachList) {
		this.workAttachList = workAttachList;
	}

	public CommonsMultipartFile getFile() {
		return file;
	}

	public void setFile(CommonsMultipartFile file) {
		this.file = file;
	}

	public String getUploaderId() {
		return uploaderId;
	}

	public void setUploaderId(String uploaderId) {
		this.uploaderId = uploaderId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSessionid() {
		return sessionid;
	}

	public void setSessionid(String sessionid) {
		this.sessionid = sessionid;
	}

	public String getAttachId() {
		return attachId;
	}

	public void setAttachId(String attachId) {
		this.attachId = attachId;
	}

	 public String getSwfFileName() {
		return swfFileName;
	}

	public void setSwfFileName(String swfFileName) {
		this.swfFileName = swfFileName;
	}

	public String getAnnexId() {
		return annexId;
	}

	public void setAnnexId(String annexId) {
		this.annexId = annexId;
	}

	public String getJsonStr() {
		return jsonStr;
	}

	public void setJsonStr(String jsonStr) {
		this.jsonStr = jsonStr;
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public String getImageSrc() {
		return imageSrc;
	}

	public void setImageSrc(String imageSrc) {
		this.imageSrc = imageSrc;
	}

}
